#!/usr/bin/python
# Created by Juan C. Espinoza <jucar.espinoza@gmail.com> March 1, 2015

import os
import argparse
from joblib import Parallel, delayed

from lisn_utils import plotter, S4Data, LISNRequest, GPSDateTime

INPUT = '/data1/gps/'
OUTPUT = '/data1/products/s4map/'

req = LISNRequest(debug=False)
sites = req.stations(instrument='gps', network='LISN,UNIVAP')

def s4map(date, args):
    '''
    '''    
    print 'Creating S4 maps for %s' % date
    S4 = []
    for site in sites:
        if args.realtime:
            filename = os.path.join('/data/temp/realtime/%s.s4' % site['code'])
        else:
            filename = os.path.join(INPUT, '%s/%s/%s/scint/%s_%s.s4.gz' % (site['network'], 
                                                                           site['code'], 
                                                                           date.strftime('%Y/%m'),
                                                                           site['code'],
                                                                           date.strftime('%y%m%d')))
            
        if not os.path.exists(filename):
            continue
        try:    
            s4 = S4Data(filename, station=site)
            s4.calcll()
        except:
            print 'Error processing: %s' % filename
            continue        
        S4.append(s4)
        
    for j in range(args.numfig):
        dt = date+args.delta*60*j
        if args.realtime:
            figname = '/data/temp/realtime/s4_map_%s.png' % dt.strftime('%H%M')
        else:
            figname = os.path.join(OUTPUT, '%s/s4_%s.png' % (dt.strftime('%Y/%m/%d'),
                                                             dt.strftime('%y%m%d_%H%M'),))
        if not args.overwrite and os.path.exists(figname):
            continue
        
        plotter.plot_s4_map(S4, dt, delta=args.delta, figname=figname, 
                            prns=args.prns, min_s4=args.min_s4, min_ele=args.min_ele,
                            threshold=2)
    
    if not args.realtime:
        req.update_date('P', 'products', 's4map', date=dt.strftime('%y%m%d'))

def main():
    '''
    Plot Scintillation S4 maps for South America.
    '''
    parser = argparse.ArgumentParser(description=main.func_doc)
    # add options and arguments
    parser.add_argument('dates', nargs='*', default=[],
        help='Period of time to be processed (start and end date) fmt:yy,mm,dd')
    parser.add_argument('-N', '--nproc', action='store', default=8, type=int,
            help='stations four-char codes')
    parser.add_argument('-r', '--realtime', action='store_true', default=False,
            help='Create realtime map')
    parser.add_argument('-o', '--overwrite', action='store_true', default=False,
            help='Overwrite figures')
    parser.add_argument('-d', '--delta', action='store', default=30, type=int,
            help='Time delta in minutes')
    parser.add_argument('-n', '--numfig', action='store', default=48, type=int,
            help='Number of figures (maps)')
    parser.add_argument('-p', '--prns', action='store', default=None,
            help='List of PRN to be plotted')
    parser.add_argument('-s', '--min_s4', action='store', default=0.15, type=float,
            help='Mask values to s4>min_s4')
    parser.add_argument('-e', '--min_ele', action='store', default=30, type=int,
            help='Mask values to elevation>min_ele')
    
    args = parser.parse_args()
    
    if len(args.dates)>0 :
        try:
            date_1 = GPSDateTime(args.dates[0])
            if len(args.dates)==2:
                date_2 = GPSDateTime(args.dates[1])
            else:
                date_2 = date_1
        except:
            parser.error('Dates can not be parsed fmt: yyyy,mm,dd')
    else:
        if args.realtime:
            date_1 = GPSDateTime().replace(second=0, microsecond=0)-60*60
        else:
            date_1 = GPSDateTime().date()-timedelta(1)
        date_2 = date_1
    
    if args.prns is not None:
        args.prns = args.prns.split(',')
    
    dates = [date_1+60*60*24*x for x in range(int(date_2-date_1)/(60*60*24)+1)]
    Parallel(n_jobs=args.nproc)(delayed(s4map)(dt, args) for dt in dates)

if __name__ == "__main__":
    dt = GPSDateTime()
    print '\n Start at %s' % GPSDateTime().ctime()
    main()
    print '\n Total secs: %s' % (GPSDateTime()-dt)
    